﻿namespace _24_Hour_Blogger.Web.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Security;
    using _24_Hour_Blogger.Web.Models;
    using WebMatrix.WebData;

    [Authorize]
    public class AccountController : Controller
    {
        // GET: /Account/Index
        public ActionResult Index()
        {
            return this.View();
        }

        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login()
        {
            return this.View();
        }

        // POST: /Account/Login
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (this.Url.IsLocalUrl(returnUrl))
                    {
                        return this.Redirect(returnUrl);
                    }
                    else
                    {
                        return this.RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return this.View(model);
        }

        // GET: /Account/LogOff
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return this.RedirectToAction("Index", "Home");
        }

        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            return this.View();
        }

        // POST: /Account/Register
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                bool error = false;
                string confirmationToken = string.Empty;
                try
                {
                    confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = "Scott", LastName = "Foster", model.Email }, false);

                    error = true;

                    if (!error)
                    {
                        try
                        {
                            var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider;
                            if (!roles.GetRolesForUser(model.UserName).Contains("Guest"))
                            {
                                roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Guest" });
                            }
                        }
                        catch (Exception)
                        {
                            // if there is a failure at this point, the user needs to be deleted.
                            // todo : encapsulate in inherited websecurity implementation
                            // credit SimpleSecurity project
                            {
                                var roleProvider = (SimpleRoleProvider)Roles.Provider;
                                var membership = (SimpleMembershipProvider)Membership.Provider;
                                string[] roles = roleProvider.GetRolesForUser(model.UserName);
                                if (roles.Length > 0)
                                {
                                    string[] users = { model.UserName };
                                    roleProvider.RemoveUsersFromRoles(users, roles);
                                }

                                membership.DeleteAccount(model.UserName);
                                bool wasDeleted = membership.DeleteUser(model.UserName, true);
                            }
                        }

                        if (!error)
                        {
                            // Login User
                            FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);

                            // Return to Home
                            return this.RedirectToAction("Index", "Home");
                        }
                        else
                        {
                            model.ErrorMessage = "An error has been encountered and logged during saving your profile, please contact our support group";
                            ModelState.AddModelError(string.Empty, model.ErrorMessage);
                        }
                    }
                }
                catch (MembershipCreateUserException ex)
                {
                    ModelState.AddModelError(string.Empty, ErrorCodeToString(ex.StatusCode));
                }
                catch (Exception)
                {
                    model.ErrorMessage = "An error has been encountered and logged during saving your profile, please contact our support group";
                    ModelState.AddModelError(string.Empty, model.ErrorMessage);
                }
            }

            // If we got this far, something failed, redisplay form
            return this.View(model);
        }

        // GET: /Account/ChangePassword
        public ActionResult ChangePassword()
        {
            return this.View();
        }

        // POST: /Account/ChangePassword
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return this.RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return this.View(model);
        }

        // GET: /Account/ChangePasswordSuccess
        public ActionResult ChangePasswordSuccess()
        {
            return this.View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
